package it.uni.bo.monitoring.protocol.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;

import static it.uni.bo.monitoring.service.StaticFields.*;

public class UDPServer extends Thread {

	private BlockingQueue<byte[]> udpQueue;
	private Logger l;
	private static final String ERROR_UDP="UDPServer: non posso inserire un pacchetto UDP";
	
	public UDPServer(BlockingQueue<byte[]> udpQueue) {
		l = Logger.getLogger(this.getClass());
		this.udpQueue= udpQueue;	
	}
	
	public synchronized void run() {	
		DatagramSocket serverSocket = null;
		try {		
			serverSocket = new DatagramSocket(UDP_PORT);
			while(true)
			{
				byte[] receiveData = new byte[UDP_PACK_SIZE];
				DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
				serverSocket.receive(receivePacket);
				udpQueue.put(receivePacket.getData());
				//String received = new String(receivePacket.getData(), 0, receivePacket.getLength());
				//l.info(received);
			}
		} catch (IOException e) {
			if(serverSocket!=null)
				if(!serverSocket.isClosed())
					serverSocket.close();
			l.error(ERROR_UDP+" "+e.getMessage());
		} catch (InterruptedException e) {
			l.error(ERROR_UDP+" "+e.getMessage());
		}
	}
	
}
